#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QTcpSocket;  //创建socket对象

    this->setWindowTitle("WheelChair_Navigation");
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_connectButton_clicked()
{
    //获取ip地址和端口号
    QString IP = ui->ipLineEdit->text();
    QString PORT = ui->portLineEdit->text();

    // 移除之前的信号处理程序
    socket->disconnect(SIGNAL(connected()));
    socket->disconnect(SIGNAL(disconnected()));

    //连接服务器
    socket->connectToHost(QHostAddress(IP), PORT.toShort());

    //连接服务器成功，socket对象会发出信号
    connect(socket, &QTcpSocket::connected, [this]()
    {
        QMessageBox::information(this, "连接提示", "服务器连接成功");
    });

    //连接断开，socket会发出信号
    connect(socket, &QTcpSocket::disconnected, [this]()
    {
        QMessageBox::warning(this, "连接提示", "服务器连接断开");
    });

}

void Widget::on_disconnectButton_clicked()
{
    //断开连接
    socket->disconnectFromHost();
}

void Widget::on_sendButton_1_clicked()
{
    // 构建JSON数据
    jsonCommand["x"] = ui->xLineEdit_1->text().toDouble();
    jsonCommand["y"] = ui->yLineEdit_1->text().toDouble();
    jsonCommand["theta"] = ui->thetaLineEdit_1->text().toDouble();

    // 将JSON数据转换为字节数组
    QJsonDocument doc(jsonCommand);
    QByteArray jsonData = doc.toJson();

    // 发送数据
    socket->write(jsonData);
}

void Widget::on_refreshButton_1_clicked()
{
    ui->xLineEdit_1->setText(QString::number(0.0));
    ui->yLineEdit_1->setText(QString::number(0.0));
    ui->thetaLineEdit_1->setText(QString::number(0.0));

}
